package com.weir.resources.permissions.utils;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.List;

/**
 * IP 工具类
 *
 * @author 老马啸西风
 * @since 1.0.0
 */
public final class IpUtil {

    private IpUtil(){}

    /**
     * 获取所有的 IP 信息
     * @param request 入参
     * @return 结果
     * @since 0.0.3
     */
//    public static IpInfo getAllIpInfo(HttpServletRequest request) {
//        IpInfo ipInfo = new IpInfo();
//        ipInfo.setClientIp(request.getHeader("X-Client-IP"));
//        ipInfo.setRealIP(request.getHeader("X-Real-IP"));
//        ipInfo.setRealIp(request.getHeader("X-Real-Ip"));
//        ipInfo.setWlProxyClientIP(request.getHeader("WL-Proxy-Client-IP"));
//        ipInfo.setProxyClientIp(request.getHeader("PROXY_CLIENT_IP"));
//        ipInfo.setForwardedFor(request.getHeader("X_Forwarded_For"));
//        ipInfo.setRemoteAddress(request.getRemoteAddr());
//        return ipInfo;
//    }

    /**
     * 获取 ip 信息
     * @param request 请求
     * @return 结果
     * @since 1.0.0
     */
    private String getIp(HttpServletRequest request) {
        List<String> keyList = Arrays.asList(
                "X-Client-IP",
                "X-Real-IP",
                "X-Real-Ip",
                "WL-Proxy-Client-IP",
                "PROXY_CLIENT_IP",
                "X_Forwarded_For"
        );

        for(String key : keyList) {
            String ip = request.getHeader(key);
            // 是合法的 IP，直接返回
            if(StringUtils.isNotBlank(ip)
                && !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            }
        }

        // 结果可能为包含 , 好的多个
        return request.getRemoteAddr();
    }

    /**
     * 获取 ip 信息
     * @param request 请求
     * @return 结果
     * @since 1.0.0
     */
    private String getSingleIp(HttpServletRequest request) {
        String ip = getIp(request);

        if(ip.contains(",")) {
            return ip.split(",")[0];
        }

        return ip;
    }

}